/**
 * 优先队列
 * 继承于普通队列
 * 入队操作不再是普通的加入队尾，而是根据权重分配相应的位置
 */
const Queue = require('./queue');


class PriorityQueue extends Queue {
    constructor(arr = []) {
        //调用父类的constructor，参数传给父类constructor
        super()
        arr.forEach(item => {
            let type = typeof item
            if (type !== 'object') {
                throw new Error('队列项不是优先队列元素')
            }
            if (item.element === undefined || item.priority === undefined) {
                throw new Error('队列缺少element或priority属性')
            }
            this._insertElement(item)
        })
    }
    //重写enQueue方法
    enQueue(element, priority) {
        const priorityqueueelement = {
            element,
            priority
        }
        this._insertElement(priorityqueueelement)

    }
    // 静态私有方法
     _insertElement(priorityqueueelement) {
        //元素是否被添加
        let added = false
        if (this.isEmpty()) {
            this.arr.push(priorityqueueelement)
            added = true
        } else {
            for(let i = 0; i <= this.arr.length-1; i++) {
                if(this.arr[i].priority >= priorityqueueelement.priority) {
                    this.arr.splice(i, 0, priorityqueueelement)
                    added = true
                    break
                }
            }
        }
        if(!added) {
            this.arr.push(priorityqueueelement)
        }
    }
    toString() {
        let str = `(队头) > `
        this.arr.forEach(item => {
            str += `${item.element} > `
        })
        return `${str} (队尾)`
    }
}

module.exports = PriorityQueue





// 测试用例
// let arr = [
//     {element: 'jam1', priority: 1},
//     {element: 'jam4', priority: 4},
//     {element: 'jam2', priority: 2},
//     {element: 'jam5', priority: 5},
//     {element: 'jam10', priority: 10},
//     {element: 'jam3', priority: 3}
// ]
// let pq = new PriorityQueue(arr)
// pq.enQueue('aaa', 6)
// pq.deQueue()
// console.log(pq.toString());
